import 'dart:convert';
import 'dart:io';
import 'package:dio/dio.dart';
import 'package:flutter/services.dart';
import 'package:image_gallery_saver/image_gallery_saver.dart';
import 'package:friends_flutter/utils/platform_utils.dart';

import 'date_utils.dart';
import 'loding.dart';
import 'log_utils.dart';


///
///@description
/// 文件帮助类
///
class FileUtils {
  ///保存图片
  ///isHttp?imgContent为http图片地址：否则是base64图片数据
  static Future<bool> saveImg(String imgContent, bool isHttp) async {
    bool flag = false;
    bool b = await PlatformUtils.permissionStorage();
    if (b) {
      late Uint8List bytes;
      if (isHttp) {
        var response = await Dio().get(imgContent, options: Options(responseType: ResponseType.bytes));
        bytes = Uint8List.fromList(response.data);
      } else {
        bytes = base64.decode(imgContent);
      }
      final result = await ImageGallerySaver.saveImage(Uint8List.fromList(bytes), quality: 100, name: XdDateUtils.getCurrTimeStamp().toString());
      LogUtilTool.println(result.toString());
      if (Platform.isIOS) {
        if (result['isSuccess']) {
          xdShowToast('保存成功');
          flag = true;
        } else {
          xdShowToast('保存失败');
        }
      } else {
        if (result != null) {
          xdShowToast('保存成功');
          flag = true;
        } else {
          xdShowToast('保存失败');
        }
      }
    } else {
      xdShowToast('未打开相册权限,请去系统设置打开');
    }
    return flag;
  }

  static Future<bool> saveImage(Uint8List pngBytes) async {
    bool flag = false;
    bool b = await PlatformUtils.permissionStorage();
    if (b) {
      final result = await ImageGallerySaver.saveImage(pngBytes, quality: 100, name: XdDateUtils.getCurrTimeStamp().toString());
      LogUtilTool.println(result.toString());
      if (Platform.isIOS) {
        if (result['isSuccess']) {
          xdShowToast('保存成功');
          flag = true;
        } else {
          xdShowToast('保存失败');
        }
      } else {
        if (result != null) {
          xdShowToast('保存成功');
          flag = true;
        } else {
          xdShowToast('保存失败');
        }
      }
    } else {
      xdShowToast('未打开相册权限,请去系统设置打开');
    }
    return flag;
  }

  //已复制到粘贴板
  static void copyClipboard(String text) {
    ClipboardData data = ClipboardData(text: text);
    Clipboard.setData(data);
    xdShowToast('复制成功');
  }

}